<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="queryParams.params.keyword"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="queryParams.params.storeId" clearable>
          <el-option
            v-for="store in stores"
            :key="store.id"
            :label="store.storeName"
            :value="store.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-cascader
          v-model="queryParams.categoryId"
          @change="handleQueryChange"
          :options="categorys"
          :props="{ checkStrictly: true }"
          :show-all-levels="false"
          clearable>
        </el-cascader>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goods:add']"
        >添加物品
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-s-home"
          size="mini"
          @click="handleStoreList()"
        >仓库管理
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-wallet"
          size="mini"
          @click="handleCategoryList()"
        >分类管理
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column width="55" align="center"/>
      <el-table-column label="序号" type="index" align="center"/>
      <el-table-column label="物品" align="center" prop="goodsCover">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodsCover" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="goodsName"/>
      <el-table-column label="品牌" align="center" prop="brand"/>
      <el-table-column label="分类" align="center" prop="categoryName"/>
      <el-table-column label="描述" align="center" prop="goodsDesc"/>
      <el-table-column label="数量" align="center" prop="amounts"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goods:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goods:remove']"
            v-if="scope.row.amounts === 0"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-truck"
            @click="handleStockList(scope.row)"
          >出入库明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入物品名称"/>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-cascader
            v-model="form.busis"
            @change="HandleChange"
            :options="categorys"
            :props="{ checkStrictly: true }"
            :show-all-levels="false"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌"/>
        </el-form-item>
        <el-form-item label="图片" prop="goodsCover">
          <image-upload v-model="form.goodsCover"/>
        </el-form-item>
        <el-form-item label="描述" prop="goodsDesc">
          <el-input type="textarea" v-model="form.goodsDesc" placeholder="请输入描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">立即提交</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="出入库明细表" :visible.sync="openCategory" width="70%" append-to-body>
      <el-table v-loading="loading" :data="categoryForm">
        <el-table-column
          type="index"
          label="序号"
          align="center">
        </el-table-column>
        <el-table-column label="类型" align="center" prop="type" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.output_input_storage" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="center" prop="operateDate" />
        <el-table-column label="物品" align="center" prop="goodsName" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="仓库" align="center" prop="storeName" />
        <el-table-column label="数量" align="center" prop="amounts" />
        <el-table-column label="单价" align="center" prop="price" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/goods/goods";
import {listAllCategory} from "../../../api/goods/category";
import {listAllStore} from "../../../api/goods/store";
import {goodsStock} from "../../../api/goods/stockBill";

export default {
  name: "Goods",
  dicts: ['output_input_storage'],
  data() {
    return {
      categorys: [],
      stores: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openCategory: false,
      // 查询参数
      queryParams: {
        params: {},
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        categoryId: null,
      },
      // 表单参数
      form: {},
      categoryForm: {},
      // 表单校验
      rules: {
        goodsName: [
          {required: true, message: "门店名称不能为空", trigger: "blur"},
          {max: 20, message: '用户名称长度不能超过50字', trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: "分类不能为空", trigger: "blur"}
        ],
        goodsCover: [
          {required: true, message: "图片不能为空", trigger: "blur"},
        ],
      }
    };
  },
  created() {
    this.getList();

    listAllCategory().then(res => {
      this.categorys = res.data;
    });

    listAllStore().then(res => {
      this.stores = res.data;
    });
  },
  methods: {
    handleQueryChange(value) {
      if (value != undefined) {
        this.queryParams.categoryId = value[value.length - 1];
      }
    },
    HandleChange(value) {
      if (value != undefined) {
        this.form.categoryId = value[value.length - 1];
      }
    },
    /* 仓库管理路由跳转 */
    handleStoreList(){
      this.$router.push({path:`/goods/store`})
    },
    /* 分类管理路由跳转 */
    handleCategoryList(){
      this.$router.push({path:`/goods/category`})
    },
    handleStockList(row) {
      this.loading = true;
      let id = row.id;
      goodsStock(id).then(res => {

        this.categoryForm = res.data;
        this.openCategory = true;
        this.loading = false;
      })
    },
    /** 查询物品信息列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openCategory = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        goodsCover: null,
        categoryId: null,
        brand: null,
        spec: null,
        goodsDesc: null,
        busiPath: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        params: {
          keyword: undefined,
          storeId: undefined
        },
        categoryId: undefined
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;

        let busiPath = this.form.params.busiPath;
        if (busiPath.includes(":")) {
          this.form.busis = busiPath.split(":")
          this.form.busis.length -= 1;
          console.log(this.form.busis)
        }

        this.open = true;
        this.title = "修改物品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物品信息编号为"' + ids + '"的数据项？').then(function () {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
